package com.zfl.utils;

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;

import java.io.FileInputStream;
import java.io.InputStream;

public class AliOssUtil {

    // Endpoint以北京为例，其它Region请按实际情况填写。
    private static final String END_POINT = "https://oss-cn-beijing.aliyuncs.com";
    // 直接指定访问密钥，无需依赖环境变量
    private static final String ACCESS_KEY_ID = "LTAI5tG3uHVEv4TezmL12rBw";
    private static final String ACCESS_KEY_SECRET = "3ZGqku4vSolZhjJvho8nG3WtxANpxZ";
    // 填写Bucket名称
    private static final String BUCKET_NAME = "big-event-zfl";
    // 填写Bucket所在地域。以华东1（杭州）为例，Region填写为cn-hangzhou。
    private static final String REGION = "cn-beijing";

    private AliOssUtil() {}

    public static String uploadFile(String objectName, InputStream in) throws Exception {



        // 创建OSSClient实例。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        // 使用DefaultCredentialProvider直接传入AccessKey
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(END_POINT)
                .credentialsProvider(new DefaultCredentialProvider(ACCESS_KEY_ID, ACCESS_KEY_SECRET))
                .clientConfiguration(clientBuilderConfiguration)
                .region(REGION)
                .build();

        String url = "https://"+BUCKET_NAME+"."+END_POINT.substring(END_POINT.lastIndexOf("/")+1)+"/"+objectName;
        try {

            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, objectName, in);

            // 上传字符串。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            System.out.println("文件上传成功");
            
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return url;
    }
}
